package com.zsck.commonbase.http.factory;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.zsck.zsgy.base.BaseResponse;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class GsonResponseBodyConverter < T > implements Converter<ResponseBody,
        T > {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    /**
     * 针对数据返回成功、错误不同类型字段处理
     */
    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            String code = result.getCode();
            String message=result.getMessage();
            if (TextUtils.equals("0",code)) {
                return gson.fromJson(response, type);
            } else {
                throw  new ResultException(code,message);
            }
        } finally {
            value.close();
        }
    }
}
